//
// Created by 文道江 on 15/12/21.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "UploadManager.h"
#import "URLSessionManager.h"


@implementation UploadManager {
    NSString *_uploadURL;
    NSString *_formName;
}

+ (UploadManager *)defaultManager {
    static UploadManager *_instance = nil;

    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }

    return _instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        //_uploadURL = @"http://192.168.1.10/upload.php";
        _uploadURL = @"http://test.api.maosui.com/Upload/File.json?ConfigId=common&Key=dfadfasfdasdfe2134sdfsadf";
        _formName = @"file";
    }

    return self;
}

- (instancetype)initWithUploadURL:(NSString *)uploadURL formName:(NSString *)formName {
    self = [super init];
    if (self) {
        _uploadURL = uploadURL;
        _formName = formName;
    }

    return self;
}

+ (instancetype)managerWithUploadURL:(NSString *)uploadURL formName:(NSString *)formName {
    UploadManager *manager = [self defaultManager];
    [manager setUploadURL:uploadURL formName:formName];
    return manager;
}

- (void)setUploadURL:(NSString *)uploadURL formName:(NSString *)formName{
    if (_uploadURL)_uploadURL = uploadURL;
    if (_formName)_formName = formName;
}


- (void)uploadFile:(NSURL *)fileURL{
    [self uploadFile:fileURL parameters:@{} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        NSLog(@"%@,%@,%@", response, responseObject, error);
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",result);
    } sendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"upload progress %lli, %lli", totalBytesSent, totalBytesExpectedToSend);
    }];
}

- (void)uploadFile:(NSURL *)fileURL
        parameters:(NSDictionary *)parameters
 completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
        sendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block{

    if (!_uploadURL){
        completionHandler(nil, nil, [NSError errorWithDomain:@"未配置 upload url" code:0 userInfo:nil]);
        return;
    }


    URLSessionManager *manager = [URLSessionManager manager];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
                                                                         URLString:_uploadURL
                                                                        parameters:parameters
                                                         constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {

                                                             NSString *mimeType = [URLUtils fileMIMEType:fileURL.path];
                                                             [formData appendPartWithFileURL:fileURL name:_formName fileName:[NSString stringWithFormat:@"%@",fileURL.lastPathComponent] mimeType:mimeType error: nil];
                                                         }];

    [[manager uploadTaskWithStreamedRequest:request progress:NULL completionHandler:completionHandler] resume];
    [manager setTaskDidSendBodyDataBlock:block];
}

@end